import React from 'react';
import { connect } from 'react-redux';
import * as routerActions from 'react-router-redux';
import { mapConfig } from 'Constants/mapConstants';

class Map extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      zoom: 16,
    };
    this.MapClick = ::this.MapClick;
    this.initMap = ::this.initMap;
    this.onLoad = ::this.onLoad;
  }
  componentDidMount() {
    this.initMap();
    this.onLoad();
  }
  initMap() {
    //经纬度地图显示；
    this.map = new T.Map('mapContent');
    //双击放大地图；
    this.map.enableDoubleClickZoom();
    //地图滚轮缩放；
    this.map.enableScrollWheelZoom();
    //地图惯性拖拽；
    this.map.enableInertia();
    //创建比例尺控件对象
    const scale = new T.Control.Scale();
    //添加比例尺控件
    this.map.addControl(scale);
  }
  onLoad() {
    //先清除地图覆盖物，在显示
    this.map.clearOverLays();
    //设置显示地图的中心点和级别
    this.map.centerAndZoom(new T.LngLat(mapConfig.longitude, mapConfig.latitude), this.state.zoom);
    this.removeMapClick();
    this.map.addEventListener('click', this.MapClick);
  }
  removeMapClick() {
    this.map.removeEventListener('click', this.MapClick);
  }
  MapClick(e) {
    // 获取点击处的名字
    //创建对象
    const geocode = new T.Geocoder();
    geocode.getLocation(e.lnglat, this.searchResult.bind(this));
    const mapAddr = {
      lng: e.lnglat.getLng(),
      lat: e.lnglat.getLat()
    };
    sessionStorage.setItem('mapAddr', JSON.stringify(mapAddr));
  }
  searchResult(result) {
    const formValue = JSON.parse(sessionStorage.getItem('MapBeforeInfo'));
    const item = {
      address: result.getAddress()
    };
    const newFormValue = { ...formValue, ...item };
    sessionStorage.setItem('MapBeforeInfo', JSON.stringify(newFormValue));
    this.props.dispatch(routerActions.goBack());
  }
  render() {
    return (
      <div className="tlypica-plan-page">
        <div className="choose-map">
          <div className="map" id="mapContent" />
        </div>
      </div>
    );
  }
}
function mapStateToProps(state) {
  return {
    ...state.routing,
    ...state.mapReducer
  };
}

export default connect(mapStateToProps)(Map);
